package com.acaslless.core.domain;

import com.acaslless.core.enums.ResultEnum;
import lombok.Getter;

import java.io.Serializable;

/**
 * 通用响应体
 *
 * @author haohan
 * @date 2024/7/29 14:09
 **/
public class R<T> implements Serializable {

    private static final long serialVersionUID = -834563756640582912L;

    private Integer code;

    @Getter
    private String msg;

    @Getter
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
    }

    public static <T> R<T> flag(boolean result) {
        return result ? ok() : error();
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, ResultEnum.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> error() {
        return restResult(null, ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
    }

    public static <T> R<T> error(String msg) {
        return restResult(null, ResultEnum.FAIL.getCode(), msg);
    }

    public static <T> R<T> error(T data) {
        return restResult(data, ResultEnum.FAIL.getCode(), null);
    }

    public static <T> R<T> error(T data, String msg) {
        return restResult(data, ResultEnum.FAIL.getCode(), msg);
    }

    public static <T> R<T> error(Integer code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> R<T> error(ResultEnum result) {
        return error(result.getCode(), result.getMsg());
    }

    private static <T> R<T> restResult(T data, Integer code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public int getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> boolean isError(R<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> boolean isSuccess(R<T> ret) {
        return ResultEnum.SUCCESS.getCode() == ret.getCode();
    }
}
